export const radioTypeData = [
  { label: "显示所有权限(角色+账号)", value: "all" },
  { label: "只显示角色权限", value: "role_owner" },
  { label: "只显示账户自定义权限", value: "user_owner" },
]
export const cascaderProps = {
  cascaderProps: {
    multiple: true,
    emitPath: false,
    label: "name",
    value: "id",
    children: "sub",
  },
  useCascaderProps: {
    emitPath: false,
    multiple: true,
    label: "name",
    value: "id",
    children: "sub",
  },
  goodsProps: {
    label: "name",
    children: "son",
  },
  goodsSearchProps: {
    multiple: true,
    emitPath: false,
    value: "id",
    label: "name",
    children: "son",
  },
  warehouseProps: {
    label: "warehouse_name",
    children: "warehouse",
  },
  warehouseSearchProps: {
    multiple: true,
    emitPath: false,
    value: "warehouse_id",
    label: "warehouse_name",
    children: "warehouse",
  },
  menuProps: {
    label: "name",
    children: "sub",
  },
  menuSearchProps: {
    multiple: true,
    emitPath: false,
    value: "id",
    label: "name",
    children: "sub",
  },
}

//递归调用
// export const treeToArray1 = (tree) => {
//   const expanded = (datas) => {
//     if (datas && datas.length > 0) {
//       datas.forEach((e) => {
//         if (e.warehouse_id) {
//           e.id = "1-" + e.warehouse_id;
//         }
//         e.label = e.attribute_name ? e.attribute_name : e.warehouse_name;
//         expanded(e.warehouse);
//       });
//     }
//   };
//   expanded(tree);
// };

export function recursivelyAddDisabled(data, falge = false) {
  // 检查数据是否为数组
  if (Array.isArray(data)) {
    // 如果是数组，递归处理数组中的每个元素
    data.forEach((item) => {
      // 为每个元素添加 disabled 属性，并将其设为 false
      item.disabled = falge
      // 如果元素有子项（假设子项的键为 children），继续递归处理子项
      if (item.children) {
        recursivelyAddDisabled(item.children)
      }
    })
  } else if (typeof data === "object") {
    // 如果数据是对象，检查对象是否有子项（假设子项的键为 children）
    if (data.children) {
      // 为对象添加 disabled 属性，并将其设为 false
      data.disabled = falge
      // 继续递归处理子项
      recursivelyAddDisabled(data.children)
    }
  }
  return data
}
export function transformData(data) {
  if (Array.isArray(data)) {
    return data.map((item) => {
      if (item.attribute_id) {
        item.warehouse_id = `1-${item.attribute_id}`
        delete item.attribute_id
      }
      if (item.attribute_name) {
        item.warehouse_name = item.attribute_name
        delete item.attribute_name
      }
      return item
    })
  }
  return data
}
//树型数据转为一维数组
export const oneArray = (tree) => {
  const arr = []
  const expanded = (datas) => {
    if (datas && datas.length > 0) {
      datas.forEach((e) => {
        if (e.son) {
          arr.push(e)
        }
        expanded(e.son)
      })
    }
  }
  expanded(tree)
  return arr
}

//树型数据的部门id特殊处理
export function convertIdToDid(nodes) {
  return nodes.map((node) => {
    // 如果节点的organization_type等于1，则修改id
    if (node.field_type === 1) {
      node.id = `d${node.id}`
    }

    // 如果存在子节点数组sub，则递归处理
    if (node.sub && Array.isArray(node.sub)) {
      node.sub = convertIdToDid(node.sub)
    }
    return node
  })
}
export function updateDepartmentIds(tree) {
  const userIdCount = {}
  const duplicateUserIds = []
  const processTree = (nodes) => {
    return nodes.map((node) => {
      const newNode = { ...node }
      if (newNode.organization_type === 1) {
        newNode.id = `d${newNode.id}`
      }
      if (newNode.organization_type === 2) {
        const originalId = newNode.id
        userIdCount[originalId] = (userIdCount[originalId] || 0) + 1
        if (userIdCount[originalId] > 1) {
          newNode.id = `${originalId}_${userIdCount[originalId] - 1}`
        }
      }
      if (Array.isArray(newNode.sub) && newNode.sub.length > 0) {
        newNode.sub = processTree(newNode.sub)
      }

      return newNode
    })
  }
  const updatedTree = processTree(tree)
  for (let userId in userIdCount) {
    if (userIdCount[userId] > 1) {
      duplicateUserIds.push({ [userId]: userIdCount[userId] })
    }
  }

  return { updatedTree, duplicateUserIds }
}

export function transformIds(obj, arr) {
  return arr.flatMap((id) => {
    const item = obj.find((o) => o.hasOwnProperty(id))

    if (item) {
      const count = item[id]
      return [id, ...Array.from({ length: count - 1 }, (_, index) => `${id}_${index + 1}`)]
    }
    return [id]
  })
}

export function simplifyIds(arr) {
  const result = []
  const seen = new Set()
  arr.forEach((item) => {
    const baseId = item.toString().split("_")[0]
    if (!seen.has(baseId)) {
      result.push(Number(baseId))
      seen.add(baseId)
    }
  })

  return result
}

export function filterTreeByIds(tree, ids) {
  let result = []
  tree.forEach((node) => {
    if (ids.includes(node.id)) {
      const filteredNode = {
        id: node.id,
        name: node.name,
        organization_type: node.organization_type,
      }
      if (node.sub) {
        const filteredChildren = filterTreeByIds(node.sub, ids)
        if (filteredChildren.length > 0) {
          filteredNode.sub = filteredChildren
        }
      }
      result.push(filteredNode)
    } else if (node.sub) {
      const filteredChildren = filterTreeByIds(node.sub, ids)
      if (filteredChildren.length > 0) {
        result = result.concat(filteredChildren) // 平铺符合条件的子节点
      }
    }
  })

  return result
}



/**
 * 从树中筛选包含关键词的节点及其所有父节点，保持树形结构
 * @param {Array} tree 树结构数组
 * @param {String} keyword 搜索关键词
 * @param {String} field 要搜索的字段，默认 'name'
 * @returns {Array} 树结构中匹配的子树
 */
export function filterTreeByKeyword(tree, keyword, field = 'name') {
  console.log(tree);
  console.log(keyword);
  const result = [];

  tree.forEach(node => {
    const newNode = { ...node };

    if (newNode.sub && newNode.sub.length) {
      newNode.sub = filterTreeByKeyword(newNode.sub, keyword, field);
    }

    const isMatch = newNode[field]?.includes(keyword);
    const hasMatchedChildren = newNode.sub && newNode.sub.length;

    if (isMatch || hasMatchedChildren) {
      result.push(newNode);
    }
  });

  return result;
}
